<template>
  <div class="app-container">
    <!--    <el-row>-->
    <!--      <img :src="form.storeImgs" @click="editCropper()" title="点击上传头像" class="img-circle img-lg"/>-->
    <!--      <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>-->
    <!--        <el-row>-->
    <!--          <el-col :xs="24" :md="12" :style="{height: '350px'}">-->
    <!--            <vue-cropper-->
    <!--              ref="cropper"-->
    <!--              :img="form.storeImgs"-->
    <!--              :info="true"-->
    <!--              :autoCrop="options.autoCrop"-->
    <!--              :autoCropWidth="options.autoCropWidth"-->
    <!--              :autoCropHeight="options.autoCropHeight"-->
    <!--              :fixedBox="options.fixedBox"-->
    <!--              @realTime="realTime"-->
    <!--            />-->
    <!--          </el-col>-->
    <!--          <el-col :xs="24" :md="12" :style="{height: '350px'}">-->
    <!--            <div class="avatar-upload-preview">-->
    <!--              <img :src="previews.url" :style="previews.img"/>-->
    <!--            </div>-->
    <!--          </el-col>-->
    <!--        </el-row>-->
    <!--        <br/>-->
    <!--        <el-row>-->
    <!--          <el-col :lg="2" :md="2">-->
    <!--            <el-upload action="#" :show-file-list="false" :before-upload="beforeUpload">-->
    <!--              <el-button size="small">-->
    <!--                上传-->
    <!--                <i class="el-icon-upload el-icon&#45;&#45;right"></i>-->
    <!--              </el-button>-->
    <!--            </el-upload>-->
    <!--          </el-col>-->
    <!--          <el-col :lg="{span: 1, offset: 2}" :md="2">-->
    <!--            <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>-->
    <!--          </el-col>-->
    <!--          <el-col :lg="{span: 1, offset: 1}" :md="2">-->
    <!--            <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>-->
    <!--          </el-col>-->
    <!--          <el-col :lg="{span: 1, offset: 1}" :md="2">-->
    <!--            <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>-->
    <!--          </el-col>-->
    <!--          <el-col :lg="{span: 1, offset: 1}" :md="2">-->
    <!--            <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>-->
    <!--          </el-col>-->
    <!--          <el-col :lg="{span: 2, offset: 6}" :md="2">-->
    <!--            <el-button type="primary" size="small" @click="uploadImg()">提 交</el-button>-->
    <!--          </el-col>-->
    <!--        </el-row>-->
    <!--      </el-dialog>-->
    <!--    </el-row>-->
    <el-row>
      <el-col :span="30" class="form-box">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="店铺名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="联系人" prop="contactName">
            <el-input v-model="form.contactName" />
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="form.contactPhone" />
          </el-form-item>
          <el-form-item label="营业时间" label-width="120px">
            <el-checkbox v-model="checked" @change="handleCheckBox"
              >全日</el-checkbox
            >
            <el-time-select
              placeholder="起始时间"
              v-model="form.businessTime"
              :disabled="checked"
              :picker-options="{
                start: '00:00',
                step: '00:15',
                end: '23:00',
              }"
            >
            </el-time-select>
            -
            <el-time-select
              placeholder="结束时间"
              v-model="form.closingTime"
              :disabled="checked"
              :picker-options="{
                start: '00:01',
                step: '00:15',
                end: '23:59',
              }"
            >
            </el-time-select>
          </el-form-item>
          <el-form-item
            label="位置区域"
            prop="province"
            class="distpicker-select"
          >
            <v-distpicker
              :province="form.province"
              :city="form.city"
              :area="form.area"
              @selected="onDistpicker"
            ></v-distpicker>
          </el-form-item>
          <el-form-item label="位置信息" class="location">
            <web-map
              :isShop="true"
              ref="webMap"
              :lng.sync="form.lng"
              :lat.sync="form.lat"
              :address.sync="form.address"
              :scope.sync="form.distScope"
              :points="points"
              :searchOption="{
                city: form.city,
                citylimit: true,
              }"
              @exportData="getNewPoints($event)"
            ></web-map>
          </el-form-item>
          <el-form-item label="配送范围(km)" prop="distScope">
            <el-input-number
              v-model="form.distScope"
              @change="handleChange"
              controls-position="right"
              :min="1"
            />
          </el-form-item>
          <el-row :gutter="24">
            <el-form-item label="店铺图片" prop="storeImgs">
              <el-upload
                :action="commonUploadApi"
                :accept="'.png,.jpg'"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="uploadSuccess"
                :headers="headers"
                :limit="imgLimitUpload"
                :file-list="fileList"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
          </el-row>
          <el-row :gutter="24">
            <el-form-item label="店铺资质" prop="storePapers">
              <el-upload
                :action="commonUploadApi"
                :accept="'.png,.jpg'"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview1"
                :on-remove="handleRemove1"
                :on-success="uploadSuccess1"
                :headers="headers"
                :limit="imgLimitUpload"
                :file-list="fileList1"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-row>
        </el-form>
        <el-col :span="30" style="width: 100%; text-align: center">
          <el-button type="primary" @click="submitForm">保 存</el-button>
        </el-col>
      </el-col>

      <el-table :data="newPoints" style="width: 100%" id="tableExcel">
        <el-table-column label="ID" prop="id"> </el-table-column>
        <el-table-column label="区域" prop="area"> </el-table-column>
        <el-table-column label="名称" prop="name"> </el-table-column>
        <el-table-column label="地址" prop="address"> </el-table-column>
        <el-table-column label="电话" prop="phone"> </el-table-column>
      </el-table>
    </el-row>
  </div>
</template>

<script>
import { getShopInfo, uploadAvatar, updateShop } from "@/api/system/shop";
import { listPoint } from "@/api/system/point";
import WebMap from "@/components/WebMap"; // svg component
import { VueCropper } from "vue-cropper";
import { mapGetters } from "vuex";
import { getToken } from "@/utils/auth";
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  components: { VueCropper, WebMap },
  data() {
    return {
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "修改Logo",
      imgLimitUpload: 5,
      options: {
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 200, // 默认生成截图框宽度
        autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
      },
      points: [],
      previews: {},
      form: {
        id: undefined,
        name: undefined,
        province: "安徽省",
        city: "合肥市",
        area: "蜀山区",
        address: "",
        lng: "116.397428",
        lat: "39.90923",
        contactName: undefined,
        contactPhone: undefined,
        businessTime: undefined,
        closingTime: undefined,
        distScope: 1,
        storeImgs: undefined,
        storePapers: undefined,
      },
      headers: { Authorization: "Bearer " + getToken() },
      rules: {},
      checked: false,
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      fileList1: [],
      newPoints: [],
    };
  },
  computed: {
    ...mapGetters(["commonUploadApi"]),
  },
  created() {
    listPoint().then((res) => {
      this.points = res.rows;
    });
    getShopInfo().then((response) => {
      if (response.code == 200) {
        this.form = response.data;
        //处理图片
        //图片回显
        this.fileList = [];
        this.fileList1 = [];
        if (this.form.storeImgs != null && this.form.storeImgs != "") {
          var arr = this.form.storeImgs.split(",");
          if (arr.length > 0) {
            arr.forEach((val) => {
              var data = {
                url: val,
                response: {
                  url: val,
                },
              };
              this.fileList.push(data);
            });
          }
        }
        if (this.form.storeImgs != null && this.form.storeImgs != "") {
          var arr1 = this.form.storePapers.split(",");
          if (arr1.length > 0) {
            arr1.forEach((val) => {
              var data = {
                url: val,
                response: {
                  url: val,
                },
              };
              this.fileList1.push(data);
            });
          }
        }
      }
      let that = this;
      setTimeout(function () {
        that.$refs.webMap.init(that.form.lng, that.form.lat);
        that.$refs.webMap.setRadius(that.form.distScope);
      }, 1000);
    });
  },
  methods: {
    //+++++++++++++++++++++++++++++++++++++上传商品主图操作
    handleRemove(file, fileList) {
      this.form.storeImgs = undefined;
      fileList.forEach((item) => {
        if (this.form.storeImgs == undefined) {
          this.form.storeImgs = item.response.url;
        } else {
          this.form.storeImgs = this.form.storeImgs + "," + item.response.url;
        }
      });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //多图上传成功后的钩子
    uploadSuccess(response, file, fileList) {
      if (this.form.storeImgs == undefined) {
        this.form.storeImgs = response.url;
      } else {
        this.form.storeImgs = this.form.storeImgs + "," + response.url;
      }
      console.log(this.form.storeImgs);
    },
    //资质图集
    handleRemove1(file, fileList) {
      this.form.storePapers = undefined;
      fileList.forEach((item) => {
        if (this.form.storePapers == undefined) {
          this.form.storePapers = item.response.url;
        } else {
          this.form.storePapers =
            this.form.storePapers + "," + item.response.url;
        }
      });
    },
    handlePictureCardPreview1(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //多图上传成功后的钩子
    uploadSuccess1(response, file, fileList) {
      if (this.form.storePapers == undefined) {
        this.form.storePapers = response.url;
      } else {
        this.form.storePapers = this.form.storePapers + "," + response.url;
      }
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateShop(this.form).then((response) => {
            this.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    handleSuccessPapers(response, file, fileList) {
      this.form.storePapers = response.url;
    },
    handleCheckBox() {
      if (this.checked == true) {
        this.form.businessTime = "00:00";
        this.form.closingTime = "23:59";
      } else {
        this.form.businessTime = "";
        this.form.closingTime = "";
      }
    },
    onDistpicker(data) {
      try {
        this.form.province = data.province.value;
        this.form.city = data.city.value;
        this.form.area = data.area.value;
        this.searchOption.city = data.city.value;
      } catch (e) {
        console.log("获取信息异常：" + e);
      }
    },
    onSearchResult(pois) {
      let poi = pois[0];
      this.amapConfig.markers = [];
      this.amapConfig.center = [poi.lng, poi.lat];
      this.amapConfig.markers.push([poi.lng, poi.lat]);
    },
    //改变区域范围刷新 搜索范围
    handleChange() {
      this.$refs.webMap.setRadius(this.form.distScope);
    },
    handleCheckBox() {
      if (this.checked == true) {
        this.form.businessTime = "00:00";
        this.form.closingTime = "23:59";
      } else {
        this.form.businessTime = "";
        this.form.closingTime = "";
      }
    },
    // 编辑头像
    editCropper() {
      this.open = true;
    },
    // 覆盖默认的上传行为
    requestUpload() {},
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.form.storeImgs = reader.result;
        };
      }
    },
    // 上传图片
    uploadImg() {
      this.$refs.cropper.getCropBlob((data) => {
        let formData = new FormData();
        formData.append("avatarfile", data);
        uploadAvatar(formData).then((response) => {
          this.open = false;
          console.log(response);
          this.form.storeImgs = process.env.VUE_APP_BASE_API + response.imgUrl;
          this.msgSuccess("修改成功");
          this.$refs.cropper.clearCrop();
        });
      });
    },
    // 实时预览
    realTime(data) {
      this.previews = data;
    },
    getNewPoints(value) {
      let arr = [];
      for (let i in value) {
        arr.push(...value[i]);
      }
      this.newPoints = arr;
      this.$nextTick(() => {
        this.exportExcel();
      });
    },
    exportExcel() {
      //定义导出Excel表格事件
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector("#tableExcel"));
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          "自提点区域分配.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
  },
};
</script>
<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
